<template>
  <div class="app-container">
    <el-form  :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
    <el-form-item label="日期" prop="date">
      <el-date-picker clearable
                      v-model="queryParams.date"
                      type="month"
                      value-format="yyyy-MM"
                      placeholder="请选择月份">
      </el-date-picker>
    </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="studentList" border>
      <el-table-column label="学生姓名" align="center" prop="name" fixed="left" width="120" />

      <!-- 动态生成当月每一天的列 -->
      <el-table-column
        v-for="day in dayCount"
        :key="day"
        :label="formatDay(day)"
        align="center"
        :class-name="isWeekend(day) ? 'weekend-column' : ''"
        width="150">
        <template slot-scope="scope">
          <div v-if="!isWeekend(day)" class="attendance-cell">
            <div class="attendance-item">
              <span class="time-label">早:</span>
              <dict-tag
                :options="dict.type.ya_attendance_status"
                :value="getAttendanceStatus(scope.row.name, day, 'early')" />
            </div>
            <div class="attendance-item">
              <span class="time-label">中:</span>
              <dict-tag
                :options="dict.type.ya_attendance_status"
                :value="getAttendanceStatus(scope.row.name, day, 'noon')" />
            </div>
            <div class="attendance-item">
              <span class="time-label">晚:</span>
              <dict-tag
                :options="dict.type.ya_attendance_status"
                :value="getAttendanceStatus(scope.row.name, day, 'night')" />
            </div>
          </div>
          <div v-else class="weekend-cell">
            休息日
          </div>
        </template>
      </el-table-column>
    </el-table>

<!--    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column label="日期" align="center" prop="date" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="周几" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ya_weekday" :value="scope.row.weekday"/>
        </template>
      </el-table-column>
      <el-table-column label="早" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ya_attendance_status" :value="scope.row.early"/>
        </template>
      </el-table-column>
      <el-table-column label="中" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ya_attendance_status" :value="scope.row.noon"/>
        </template>
      </el-table-column>
      <el-table-column label="晚" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ya_attendance_status" :value="scope.row.night"/>
        </template>
      </el-table-column>
    </el-table>-->

<!--    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column label="日期" align="center" prop="date" width="100" />
      <el-table-column label="上课天数(早/中/晚)" align="center" width="150">
        <template slot-scope="scope">
          {{ scope.row.dayCount }}/{{ scope.row.dayCount }}/{{ scope.row.dayCount }}
        </template>
      </el-table-column>
      <el-table-column label="出席" align="center">
        <template slot-scope="scope">
          {{ countStatus(scope.row.earlyList, 1) }}/{{ countStatus(scope.row.noonList, 1) }}/{{ countStatus(scope.row.nightList, 1) }}
        </template>
      </el-table-column>
      <el-table-column label="旷课" align="center">
        <template slot-scope="scope">
          {{ countStatus(scope.row.earlyList, 2) }}/{{ countStatus(scope.row.noonList, 2) }}/{{ countStatus(scope.row.nightList, 2) }}
        </template>
      </el-table-column>
      <el-table-column label="迟到" align="center">
        <template slot-scope="scope">
          {{ countStatus(scope.row.earlyList, 3) }}/{{ countStatus(scope.row.noonList, 3) }}/{{ countStatus(scope.row.nightList, 3) }}
        </template>
      </el-table-column>
      <el-table-column label="请假" align="center">
        <template slot-scope="scope">
          {{ countStatus(scope.row.earlyList, 4) }}/{{ countStatus(scope.row.noonList, 4) }}/{{ countStatus(scope.row.nightList, 4) }}
        </template>
      </el-table-column>
      <el-table-column label="事假" align="center">
        <template slot-scope="scope">
          {{ countStatus(scope.row.earlyList, 5) }}/{{ countStatus(scope.row.noonList, 5) }}/{{ countStatus(scope.row.nightList, 5) }}
        </template>
      </el-table-column>
      <el-table-column label="病假" align="center">
        <template slot-scope="scope">
          {{ countStatus(scope.row.earlyList, 6) }}/{{ countStatus(scope.row.noonList, 6) }}/{{ countStatus(scope.row.nightList, 6) }}
        </template>
      </el-table-column>
      <el-table-column label="线上" align="center">
        <template slot-scope="scope">
          {{ countStatus(scope.row.earlyList, 7) }}/{{ countStatus(scope.row.noonList, 7) }}/{{ countStatus(scope.row.nightList, 7) }}
        </template>
      </el-table-column>
    </el-table>-->

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  listAttendance,
  getAttendance,
  delAttendance,
  addAttendance,
  updateAttendance,
  listStuAttendance, listStuOrAll
} from "@/api/teaching/attendance";

export default {
  name: "Attendance",
  dicts: ['ya_weekday', 'ya_attendance_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考勤汇总表格数据
      attendanceList: [],
      // 学生列表数据
      studentList: [],
      // 天数
      dayCount: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询考勤汇总列表 */
    getList() {
      this.loading = true;
      listStuOrAll(this.queryParams).then(response => {
        // 获取考勤数据
        this.attendanceList = response.rows[0]?.yaAttendanceList || [];
        // 获取学生列表
        this.studentList = response.rows[0]?.studentList || [];
        // 获取天数
        this.dayCount = response.rows[0]?.dayCount || 0;

        // 生成天数数组
        this.generateDays();

        this.total = response.total;
        this.loading = false;
      });
    },

    // 生成天数数组
    generateDays() {
      // 将dayCount转换为数组 [1, 2, 3, ..., dayCount]
      this.dayCount = Array.from({length: this.dayCount}, (_, i) => i + 1);
    },

    // 格式化日期显示
    formatDay(day) {
      const date = this.queryParams.date ? new Date(this.queryParams.date + '-01') : new Date();
      const year = date.getFullYear();
      const month = date.getMonth();

      // 创建当月对应天数的日期
      const currentDate = new Date(year, month, day);

      // 获取周几
      const weekday = currentDate.getDay();
      const weekdayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

      // 格式化为 MM-DD 周X
      return `${(month + 1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${weekdayNames[weekday]}`;
    },

    // 获取考勤状态
    getAttendanceStatus(studentName, day, timeSlot) {
      // 查找对应的考勤记录
      const record = this.attendanceList.find(item => {
        // 从日期中提取天数
        const itemDay = item.date ? parseInt(item.date.split('-')[2]) : 0;
        return item.studentName === studentName && itemDay === day;
      });

      // 如果找到记录，返回对应时段的状态
      if (record) {
        return record[timeSlot];
      }

      // 默认返回空或未设置状态
      return null;
    },

    // 统计特定状态的数量
    countStatus(list, status) {
      if (!list || !Array.isArray(list)) {
        return 0;
      }
      return list.filter(item => item === status).length;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        studentName: null,
        date: null,
        className: null,
        stage: null,
        weekday: null,
        early: null,
        noon: null,
        night: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考勤汇总";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAttendance(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤汇总";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAttendance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttendance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考勤汇总编号为"' + ids + '"的数据项？').then(function() {
        return delAttendance(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teaching/attendance/export', {
        ...this.queryParams
      }, `attendance_${new Date().getTime()}.xlsx`)
    },
    // 判断是否为周末
    isWeekend(day) {
      const date = this.queryParams.date ? new Date(this.queryParams.date + '-01') : new Date();
      const year = date.getFullYear();
      const month = date.getMonth();

      // 创建当月对应天数的日期
      const currentDate = new Date(year, month, day);

      // 获取周几 (0表示周日)
      return currentDate.getDay() === 0;
    },
  }
};
</script>

<style scoped>
.attendance-cell {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.attendance-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.time-label {
  margin-right: 5px;
  font-weight: bold;
  min-width: 20px;
}

.weekend-cell {
  background-color: #f0f9eb;
  color: #909399;
  padding: 10px 0;
  font-size: 20px;
  border-radius: 10px;
}

/* 为了让表头也有相应的样式，需要添加全局样式 */
/* 周末列的表头样式 */
.weekend-column .cell {
  background-color: #f0f9eb;
  color: #67c23a;
  font-weight: bold;
}
</style>





